package com.ketti.team;

import java.util.HashMap;

import android.app.TabActivity;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ScrollView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.TabHost.TabSpec;

/**
 * @author JaeGwang Ryu
 * @since 		@version
 * 2010,04,23 	0.10	Create tab that height is height of text.
 * 2010,04,23	0.11	Apply background image for tab.
 * 2010,04,25	0.12	Create view that connected with tab.
 * 						And show this app_name and filename to app title.
 * 
 * */
public class EditorActivity extends TabActivity implements TabHost.TabContentFactory
{
	// This is widget to have tabWidget.
	private TabHost mTabHost;
	// This is repository that have filename(tag of tab) and sourceView.
	private HashMap<String, View> mSourceView;
	// This is keyword to highlight
	private final String[] keyWordList = new String[] {
			"abstract", "assert", "boolean", "break", "byte", 
			"case", "catch", "char", "class", "const",
			"continue", "default", "do", "double", "else", 
			"enum", "extends", "false", "final", "finally",
			"float", "for", "goto", "if", "implements",
            "import", "instanceof", "int", "interface", "long", 
            "native", "new", "null", "package", "private", "protected",
            "public", "return", "short", "static", "strictfp",
            "super", "switch", "synchronized", "this", "throw", "throws",
            "true", "transient", "try", "void", "volatile", "while"
            };
	private InputFilter keyWordInputFilter;
		
	/* Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
              
        /* setting tabs */
        mTabHost = getTabHost();
        // Show this app_name and filename to app title.
        mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener()
		{
			@Override
			public void onTabChanged(String tabId)
			{
				// TODO Auto-generated method stub
				Log.i("xxxxxxxxxxx","Focused [" + tabId + "] tab");
				setTitle(getResources().getText(R.string.app_name)+ " - " + tabId);
				
			}
		});
        mSourceView = new HashMap<String, View>();
        
        LayoutInflater.from(this).inflate(R.layout.main,
        		mTabHost.getTabContentView(), true);
          
        /* When app begin, show '+' tab only.*/
        createTabAndSourceView("+");        
        createTabAndSourceView("This is a test.");
        createTabAndSourceView("Sure!!");        
      }       

	/**
     * create Tab and SourceView
     * @param filename : If selecting New-menu, put "*" instead of filename.
     * 					 If selecting Open-menu, put filename.
     * */
    public void createTabAndSourceView(String filenamge)
    {
    	mSourceView.put(filenamge, createSourceView(filenamge));
       	mTabHost.addTab(createTab(filenamge)); 
     }
    
    /**
     * create new tab (Tab label is tag.)
     * @param tag : If selecting New-menu, put "*" instead of filename.
     * 				If selecting Open-menu, put filename.
     * */
    public TabSpec createTab(String tag)
    {	
    	return	mTabHost.newTabSpec(tag)
    			.setIndicator(createIndicatorViewOnlyLabel(tag))
    			.setContent(this);
    }
	
	/** 
	 * Create tab widget only label without icon.
	 * 
	 * @param label If selecting New-menu, put "*" instead of filename.
     * 				If selecting Open-menu, put filename.
	 * @return tab widget only label
	 */
	public View createIndicatorViewOnlyLabel(String label) 
	{
		// create TextView for label
		TextView tv = new TextView(this);
		tv.setGravity(Gravity.CENTER);						// set on center
		tv.setText(label);									// set text of label
		tv.setBackgroundResource(R.drawable.tab_indicator);	// set tab image
		
        // If Android version 1.6 of your device, show other tab image.
        if (this.getApplicationInfo().targetSdkVersion <= Build.VERSION_CODES.DONUT)
        {
            // Donut apps get old color scheme
            tv.setBackgroundResource(R.drawable.tab_indicator_v4);
            tv.setTextColor(this.getResources().getColorStateList(R.color.tab_indicator_text_v4));
        }
        return tv;
    }
	
	/**
	 * Create new sourceView.
	 * 
	 * @param filename If selecting New-menu, put "*" instead of filename.
     * 				   If selecting Open-menu, put filename.
     * @return EditText and first screen is TextView for title.
	 * */
	public View createSourceView(String filename)
	{
		Log.i("xxxxxxxxxxx","Created [" + filename + "] view");
		View v;
		// create titleView
		if(mSourceView.isEmpty())
		{			
			TextView titleView = new TextView(this);
			titleView.setText("Android Editor ver 0.12");
			titleView.setGravity(Gravity.CENTER_HORIZONTAL
								|Gravity.CENTER_VERTICAL);
			v = titleView;
		}
		// create sourceView
		else
		{
			/*create new instance for NewEditText class */
			ScrollView scrollView = new ScrollView(this);
			
			
			NewEditText newSourceView = new NewEditText(this);
			newSourceView.setText(R.string.test_string);
			setInitailKeyWordFilter(newSourceView, keyWordList);
			newSourceView.setTextSize(Setting.getmFontSize());
			newSourceView.setGravity(Gravity.TOP);
			newSourceView.setHorizontallyScrolling(true);
			setKeyWordInputFilter();
			newSourceView.setFilters(new InputFilter[] {keyWordInputFilter});
			
			scrollView.addView(newSourceView);
									
			v = scrollView;
		}
		return v;
	}
	
	/* Change keyword in initial source to red  */
	private void setInitailKeyWordFilter(NewEditText newSourceView,
			String[] keyWordList) {
		SpannableString source = new SpannableString(newSourceView.getText());
        
        for(String s : keyWordList){
        	if(source.toString().indexOf(s) != -1){
        		source.setSpan(new ForegroundColorSpan(Color.RED), source.toString().indexOf(s), source.toString().indexOf(s) + s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        		Log.d("match", Integer.toString(source.toString().indexOf(s)));
        	}
        }
        newSourceView.setText(source); 
	}

	/**
	 * Setup keyword filter to highlight keyword in source. if user put 
	 * some keyword to EditText, this filter automatically change this word to red 
	 **/	
	 private void setKeyWordInputFilter() {
	    	keyWordInputFilter = new InputFilter() {
				
				@Override
				public CharSequence filter(CharSequence source, int start, int end,
						Spanned dest, int dstart, int dend) {
					for(String s : keyWordList)
					{
						if(s.equals(source))
						{						
							SpannableString sp = new SpannableString(source);
							sp.setSpan(new ForegroundColorSpan(Color.RED), 0, sp.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);						
							return sp;
						}
					}
					return source;
				}
			};
		}

	/**
	 * Connect sourceView to a tab.
	 * 
	 * @param tag The tag of a tab or the filename.
	 * @return SourceView that will connect to tab. 
	 * */
	@Override
	public View createTabContent(String tag)
	{
		Log.i("xxxxxxxxxxx","To connect sourceView to [" + tag + "] tab");
		
		return mSourceView.get(tag);
	}
}